<template>
  <div class="login-wrapper">
    <el-container class="login-container">
      <el-header class="login-header">
        <h2>东软颐养中心</h2>
      </el-header>
      <el-main class="login-main">
        <el-form
            :model="form"
            :rules="rules"
            ref="loginForm"
            label-width="0"
            class="login-form"
        >
          <!-- 账号 -->
          <el-form-item prop="account" class="form-item-center">
            <div class="input-wrapper">
              <el-input
                  v-model="form.account"
                  placeholder="账号"
                  class="login-input"
              >
                <template #prefix>
                  <el-icon><User/></el-icon>
                </template>
              </el-input>
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password" class="form-item-center">
            <div class="input-wrapper">
              <el-input
                  v-model="form.password"
                  placeholder="密码"
                  show-password
                  class="login-input"
              >
                <template #prefix>
                  <el-icon><Lock/></el-icon>
                </template>
              </el-input>
            </div>
          </el-form-item>

          <el-form-item prop="captcha" class="form-item-center">
            <div class="captcha-wrapper">
              <el-input v-model="form.captcha" placeholder="请输入验证码" class="captcha-input">
                <template #prefix>
                  <el-icon><Lock/></el-icon>
                </template>
              </el-input>

              <Identify
                  ref="identifyRef"
                  :codeLength="4"
                  @update:code="updateIdentifyCode"
              />
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
                type="primary"
                @click="onSubmit"
                class="login-btn"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login , getCurrentUser } from '@/api/apiList/admin'
import { User, Lock } from '@element-plus/icons-vue'
import Identify from '@/components/Identify.vue'
import {adminName} from "@/store/user";

const router = useRouter()
const form = reactive({ account: '', password: '', captcha: '' })
const rules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 使用从子组件同步过来的 identifyCode.value 进行比较
        if (value.toLowerCase() !== identifyCode.value.toLowerCase()) {
          callback(new Error('验证码输入错误'));
          // 调用子组件暴露的 refreshCode 方法来刷新验证码
          if (identifyRef.value) {
            identifyRef.value.refreshCode();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
}
const loginForm = ref(null)
const identifyRef = ref(null); // 用于获取Identify组件的实例
const identifyCode = ref(''); // 用于存储从子组件接收到的验证码

// 重置验证码
const updateIdentifyCode = (newCode) => {
  identifyCode.value = newCode;
};

async function onSubmit() {
  await loginForm.value.validate(async valid => {
    if (!valid) return
    try {
      const token = await login(form.account, form.password)
      localStorage.setItem('token', token)
      // 2. 再去拿当前用户信息
      const admin = await getCurrentUser()
      localStorage.setItem('adminId', admin.adId)
      localStorage.setItem('adminName', admin.adName)
      adminName.value = admin.adName;
      localStorage.setItem('role', admin.role)
      // —— 新增：检测初始密码 ——
      const phone = admin.phone  // 后端返回的 admin 里要有 phone
          const suffix = phone.slice(-6)
            if (form.password === suffix) {
         ElMessage.warning('检测到您尚未修改初始密码，请先设置新密码并完善个人信息')
          // 带上一个 query，ChangePassword 页面可以拿到 adminId
        return router.replace({
              name: 'ChangePassword',
          query: { redirect: 'Welcome' }
         })
        }
      ElMessage.success('登录成功')
      router.replace({ name: 'Welcome' })
    } catch (err) {
      ElMessage.error(err.message || '登录失败')
    }
  })
}
</script>

<style scoped>
.login-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  background: url(~@/assets/图4.jpg) center/cover no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  position: relative;
  z-index: 2;
  width: 60vw;
  height: 380px;
  max-width: 400px;
  min-width: 350px;
  background: rgba(255,255,255,0.85);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-header {
  text-align: center;
  margin-bottom: 16px;
  color: #333;
}

.login-form {
  width: 100%;
}

/* 使每行输入框水平居中 */
.form-item-center {
  text-align: center;
}
.captcha-wrapper {
  display: flex; /* 关键：将容器设置为Flexbox布局 */
  align-items: center; /* 关键：让子元素在垂直方向上居中对齐 */
  width: 80%; /* 让容器占满整个 el-form-item 的宽度 */
  margin-left: 32px;
}

.captcha-input {
  flex: 1; /* 关键：让输入框占据所有剩余的可用空间 */
  margin-right: 10px; /* 在输入框和验证码之间添加一些间距 */
}

/* 包裹器锁定宽度，不让内部撑开 */
.input-wrapper {
  display: inline-block;
  width: 350px;      /* 固定宽度 */
  margin: 0 auto;
  overflow: hidden;  /* 隐藏多余部分 */
}

/* 输入框占满 wrapper */
.login-input {
  width: 80%;
  box-sizing: border-box; /* 包含 padding/border */
}

/* 登录按钮样式 */
.login-btn {
  display: block;
  width: 25%;
  min-width: 120px;
  margin: 10px auto 0;
  height: 30px;
  font-size: 15px;
  line-height: 15px;
}
</style>
